﻿using System;
using System.Threading;

namespace EveKillboard.Core
{
    public class EveCustomFormatProvider : IFormatProvider, ICustomFormatter
    {
        public static readonly EveCustomFormatProvider Instance  = new EveCustomFormatProvider();

        public object GetFormat(Type formatType)
        {
            return formatType == typeof(ICustomFormatter) ? this : null;
        }

        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            if (arg ==null || arg.GetType() != typeof(decimal))
                try
                {
                    return HandleOtherFormats(format, arg);
                }
                catch (FormatException e)
                {
                    throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
                }

            var value = (decimal) arg;

            var b = value / 1000000000;
            if (b >= 1)
            {
                return string.Format(Thread.CurrentThread.CurrentCulture, "{0:N2} B", b);
            }

            var m = value / 1000000;
            if (m >= 1)
            {
                return string.Format(Thread.CurrentThread.CurrentCulture, "{0:N2} M", m);
            }

            var k = value/1000;
            if(k >= 1)
            {
                return string.Format(Thread.CurrentThread.CurrentCulture, "{0:N2} K", k);
            }

            return string.Format(Thread.CurrentThread.CurrentCulture, "{0:N2} isk", value);
        }

        private string HandleOtherFormats(string format, object arg)
        {
            var formattable = arg as IFormattable;
            if (formattable != null)
                return (formattable).ToString(format, Thread.CurrentThread.CurrentCulture);
            return arg != null ? arg.ToString() : String.Empty;
        }
    }
}